<?php

namespace App\Http\Controllers\WeChatOauthHome\AuthManage;

use App\Models\WeChatOauthHome\AuthManage\LoginPcModel;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;

/**
 * 微信OAuth2.0登录控制类
 * Class LoginController
 * @package App\Http\Controllers
 */
class LoginPcController
{
    /**
     * 微信PC扫码登录
     * @param Request $request
     * @return false|string
     * @throws \Exception
     */
    public function loginPc(Request $request)
    {
        $relData = LoginPcModel::getPcLoginUri();
        return ApiReturn($relData);
    }

    /**
     * 绑定微信登录
     * @return false|string
     * @throws \Exception
     */
    public function pcBindWechat() {
        $relData = LoginPcModel::getPcLoginUri(APP_USER_TOKEN);
        return ApiReturn($relData);
    }

    /**
     * 微信授权登录绑定用户（回调地址）
     * @param Request $request
     * @return false|string
     * @throws \Exception
     */
    public function redirectBindLoginPc(Request $request)
    {
        $code = $request->input('code', '');
        $state = $request->input('state', '');
        $relData = LoginPcModel::userBindWechat($state, $code);
        if ($relData['code'] == RETURN_SUCCESS) {
            return redirect(__HOST__ . '/admin/wechatlogin.html');
        } else {
            return ApiReturn($relData);
        }
    }

	/**
	 * 微信授权登录（回调地址）
	 * @param Request $request
	 * @return false|string
	 * @throws \Exception
	 */
	public function redirectLoginPc(Request $request)
	{
		$code = $request->input('code', '');
		$relData = LoginPcModel::LoginUser($code);
		if ($relData['code'] == RETURN_SUCCESS) {
            return redirect(__HOST__ . '/admin/wechatlogin.html?API-SC-TOKEN=' . base64_encode($relData['data']['token']));
        } else {
            return ApiReturn($relData);
        }
	}

    /**
     * openId登录
     * @param Request $request
     */
	public function loginOpenId(Request $request) {
        $openId = $request->input('openId', '');

    }

	/**
	 * 更新当前TOKEN
	 * @return false|string
	 * @throws \Exception
	 */
	public function updateToken()
	{
		$relData = LoginPcModel::updateToken(APP_USER_TOKEN);
		return ApiReturn($relData);
	}

    /**
     * 退出登录
     * @return false|string
     * @throws \Exception
     */
	public function loginOut()
	{
		$relData = LoginPcModel::LoginOut(APP_USER_TOKEN);
		return ApiReturn($relData);
	}

    /**
     * 获取用户信息
     * @return false|string
     * @throws \Exception
     */
	public function getUserInfo()
	{
		$userInfoObj = LoginPcModel::getUserInfo(APP_USER_TOKEN);
		if ($userInfoObj['code'] != RETURN_SUCCESS) {
			return ApiReturn($userInfoObj);
		}

		$userObj = $userInfoObj['data'];
		unset($userObj['authList'], $userObj['uid']);
		return ApiReturn(RETURN_SUCCESS, "获取成功", $userObj);
	}
}
